const query = require('./mysql');

let dataTools = {
    insert: (datas) => {
        let fields = [],
            values = [];
        for (let k in datas) {
            fields.push(k)
            values.push(datas[k])
        }
        return {
            fields: `(${fields.join(",")})`,
            values: `('${values.join("','")}')`
        }
    },
    set: (sets) => {
        let values = [];
        for (let k in sets) {
            values.push(k + "= '" + sets[k] + "'")
        }
        return values.join("','")
    },
    where: (terms) => {
        let values = [];
        for (let k in terms) {
            values.push(k + "= '" + terms[k] + "'")
        }
        return values.join(" AND ")
    },
    back: (sql) => {
        return new Promise((resolve, reject) => {
            query(sql).then(res => {
                resolve(res)
            }).catch(err => {
                reject(err)
            })
        })
    }
}

/**
 * @param {String} table 表名
 * @param {Object} datas 插入数据集合
 */
let insertData = (table, datas) => {
    let val = dataTools.insert(datas);
    let sql = `INSERT INTO ${table} ${val.fields} VALUES ${val.values}`;
    return dataTools.back(sql)
}

let deleteData = (table, where) => {
    let con = dataTools.where(where);
    let sql = `DELETE FROM ${table} WHERE ${con}`;

    // console.log(sql, "Sql")
    return dataTools.back(sql)
}

let updateData = (table, sets, where) => {
    let datas = dataTools.set(sets);
    let con = dataTools.where(where);

    let sql = `UPDATE ${table} SET ${datas} WHERE ${con}`;
    console.log(sql, "Sql")
    return dataTools.back(sql)
}
/**
 * 
 * @param  {...any} args 
 * 
 * 1、参数1：String 数据表的字符串
 * 2、参数2：Array {key:value,key:value}
 * 3、参数3：Array [1,2,3]
 */
let selectData = (...args) => {
    let sql = ""
    switch (args.length) {
        case 1:
            sql = `SELECT * FROM ${args[0]}`;
            break;
        case 2:
            let where = dataTools.where(args[1])
            sql = `SELECT * FROM ${args[0]} WHERE ${where}`;
            break;
        case 3:
            let where2 = dataTools.where(args[1])
            sql = `SELECT ${args[2].join(",")} FROM ${args[0]} WHERE ${where2}`;
            break;
    }
    return dataTools.back(sql)
}

module.exports = {
    insertData,
    deleteData,
    updateData,
    selectData
}